package com.example.origin.demo.filter;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class DemoFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        ServletUtil.getHeader(request, "Cookie", Charset.defaultCharset());

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        requestAttributes.setAttribute("abc", "bcd", RequestAttributes.SCOPE_REQUEST);
        requestAttributes.registerDestructionCallback("abc", () -> {
            log.info("cache remove");
        }, RequestAttributes.SCOPE_REQUEST);
        filterChain.doFilter(request, response);
    }
}
